package main

import (
	"fmt"
	"log"

	"github.com/PuerkitoBio/goquery"
	"github.com/hu17889/go_spider/core/common/page"
	"github.com/hu17889/go_spider/core/common/request"
	"github.com/hu17889/go_spider/core/spider"
)

type Processors struct {
	crawler *spider.Spider
	reqs    []*request.Request
}

func NewProcessors(reqs []*request.Request) *Processors {
	return &Processors{
		crawler: spider.NewSpider(&Processors{}, "Processor"),
		reqs:    reqs,
	}
}

func (t *Processors) Run() {
	log.Print("获取 Intel ARK 处理器系列列表...")
	t.crawler.GetAllByRequest(t.reqs)
}

func (t *Processors) Process(p *page.Page) {
	if !p.IsSucc() {
		log.Printf("Url: %s, Err: %s", p.GetRequest().Url, p.Errormsg())
		return
	}

	q := p.GetHtmlParser()

	// $("[data-parent-panel-key='Processors'] [data-panel-key]").each((_, v) => $("[data-parent-panel-key='" + $(v).attr('data-panel-key') + "'] a").each((_, v) => console.log($(v).attr('href'))))

	var reqs []*request.Request
	q.Find("[data-parent-panel-key='Processors'] [data-panel-key]").Each(func(i int, s *goquery.Selection) {
		panelName := s.AttrOr("data-panel-key", "")
		if panelName != "" {
			q.Find(fmt.Sprintf("[data-parent-panel-key='%s'] a", panelName)).Each(func(i int, s *goquery.Selection) {
				url := fmt.Sprintf("https://ark.intel.com%+v", s.AttrOr("href", ""))

				log.Printf("%s %s", s.Text(), url)
				reqs = append(reqs, request.NewRequest(url, "html", s.Text(), "GET", "", nil, nil, nil, nil))
			})
		}
	})

	NewSeries(reqs).Run()
}

func (t *Processors) Finish() {
	log.Printf("Intel ARK 处理器系列页面已解析完毕！！！")
}
